﻿using Abp.Domain.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MyTestABP.Entities;
using Abp.Application.Services;
using MyTestABP.Classes.Dto;
using MyTestABP.IRepositories;

namespace MyTestABP.Classes
{
    public class ClassAppService : IClassAppService
    {
        private readonly IClassRepositories _classRepository;

        public ClassAppService(IClassRepositories ClassRepository)
        {
            _classRepository = ClassRepository;
        }

        //统计每个班级下有多少学生
        public List<ClassOutput> GetClassSummry() {

            List<ClassOutput> list = new List<ClassOutput>();
            //-_classRepository.
            var data = _classRepository.GetAll().Select(x => new ClassOutput
            {
                Name=x.name,
                number=x.Students.Count()
            }).ToList();
            return data;
        }

        public List<ClassDto> GetClass()
        {
            var data = _classRepository.GetAll().Select(x => new ClassDto
            {
                ID = x.Id,
                name = x.name
            }).ToList();
            return data;
        }
        public int addClass(ClassInput c)
        {
            //判断添加的实体是否存在
            if (_classRepository.Count(x => x.name == c.name) > 0)
            {
                return -1;
            }
            MyTestABP.Entities.Classes cl=new Entities.Classes();
            cl.name=c.name;
             int id=_classRepository.InsertAndGetId(cl);
             return id;
        }
        public int updateClass(updateClassInput c)
        {
            if (_classRepository.GetAll().Where(x => x.name == c.name).Count() > 0)
            {
                return 0;
            }
            MyTestABP.Entities.Classes cl = _classRepository.GetAll().Where(x=>x.Id==c.Id).FirstOrDefault();
            cl.name = c.name;
            _classRepository.Update(cl);
            return 1;

        }
        public int deleteClass(ClassInput c)
        {
            try
            {
                MyTestABP.Entities.Classes cl = _classRepository.GetAll().Where(x => x.Id == c.Id).FirstOrDefault();
                
                _classRepository.Delete(cl);
                return 1;
            }
            catch
            {
                return 0;
            }
        }

        public int classIsStudent(ClassInput c)
        {
            try
            {
                if (_classRepository.GetAllList().Where(x=>x.Id==c.Id).FirstOrDefault().Students.Count() > 0)
                    return 1;
                else
                    return 0;
            }
            catch
            {
                return -1;
            }
        }
    }
}
